package Collections;

import java.util.HashMap;
import java.util.Map;

public class MonitorVehicleTracker {
	
	private final Map<String, MutablePoint> locations;
	
	public MonitorVehicleTracker(Map<String, MutablePoint> data) {
		locations = deepCopy(data);
	}

	public synchronized MutablePoint getLocation(String name) {
		
		MutablePoint loc = safeGet(name);
		
		return new MutablePoint(loc.x, loc.y); //create a copy to forbid changes in state loc
	}
	
	public synchronized void setLocation (String name, MutablePoint point) {
		MutablePoint loc = safeGet(name);
		loc.x = point.x;
		loc.y = point.y;
//		if (name == null) throw new IllegalArgumentException();
//		if (locations.containsKey(name)){
//			locations.put(name, new MutablePoint(point.x, point.y)); //create new point to be owners of the object
//		} else {
//			throw new IllegalArgumentException("no such ID: " + name);
//		}
	}

	private MutablePoint safeGet(String name) {
		MutablePoint loc = locations.get(name);
		if (loc == null) {
			throw new IllegalArgumentException("no such ID: " + name);
		}
		return loc;
	}
	
	public Map<String, MutablePoint> getLocations() {
		return deepCopy(locations);
	}

	private Map<String, MutablePoint> deepCopy( Map<String, MutablePoint> src) {
		Map <String, MutablePoint> copy = new HashMap<String, MutablePoint>();
		for(String id : src.keySet()) {
			MutablePoint point = src.get(id);
			copy.put(id, new MutablePoint(point));
		}
		return copy;
	}
}
